#include"mythread.hpp"

// 让新线程去抢火车票

//下面的代码是有问题的！ 代码没有互斥
// 多个线程交叉执行，全局变量tickets没有被保护到，因此会出现问题


int tickets = 1000;
void* GetTicket(void* args)
{
    const char* name = static_cast<const char*>(args);
    // printf("我是线程%s, 我要开始抢票了\n", name);
    while(true)
    {
        if(tickets > 0)
        {
            //还有票可以抢
            usleep(12345); // 这里大概是0.01s
            // 1s = 1000ms = 1000000微秒 这里usleep的单位是微秒
            printf("%s正在进行抢票：%d\n", name, tickets--);
        }
        else
        {
            printf("%s发现已经没有票了\n", name);
            break;
        }
    }

    return nullptr;
}

int main()
{
    Thread* thread1 = new Thread(GetTicket, (void*)"thread1", 1);
    Thread* thread2 = new Thread(GetTicket, (void*)"thread2", 2);
    Thread* thread3 = new Thread(GetTicket, (void*)"thread3", 3);
    Thread* thread4 = new Thread(GetTicket, (void*)"thread4", 4);
    Thread* thread5 = new Thread(GetTicket, (void*)"thread5", 5);

    thread1->join();
    thread2->join();
    thread3->join();
    thread4->join();
    thread5->join();

    return 0;
}